package edu.biwu.request;

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@WebServlet("/req/upload01")
@MultipartConfig//上传文件相关的注解
public class ReqUploadDemo01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.通过requeset对象获取Part接口的实现类对象(该对象中封装了上传文件的相关信息)
        Part uploadFile = request.getPart("uploadFile");

        //2.通过Part接口的实现类对象获取上传文件的相关信息
        /*System.out.println(uploadFile.getSubmittedFileName());
        System.out.println(uploadFile.getContentType());
        System.out.println(uploadFile.getSize());*/
        String fileName = uploadFile.getSubmittedFileName();

        //3.保证存储文件名唯一，可以让用户重复上传文件
        String extension = fileName.substring(fileName.lastIndexOf("."));//截取文件的后缀名.jpg
        String newFileName = UUID.randomUUID() + extension;// 例如: asdfdf-123123-sdfasdf.jpg

        //4.规定将文件上传到D:/uploadFile文件夹下
        File file = new File("D:/uploadFile");
        if (!file.exists()) {//如果指定的上传路径在硬盘不存在,我们需要创建
            file.mkdirs();
        }

        //5.将上传的文件写入到指定的路径
        uploadFile.write(file + "/" + newFileName);

        //6.响应给客户端一个提示信息
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(fileName + "上传成功");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
